package com.zhoug.common.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.media.ThumbnailUtils;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;

import retrofit2.http.OPTIONS;

/**
 * Bitmap工具
 */
public class BitmapUtils {
    private static final String TAG = "BitmapUtils";
    private static final boolean DEBUG = false;
    /**
     * Gamma校正算法
     */
    public static final int GRAY_ALGORITHM_GAMMA = 0;
    /**
     * 浮点法 Gray=R*0.3+G*0.59+B*0.11
     */
    public static final int GRAY_ALGORITHM_FLOAT = 1;
    /**
     * 移位法 Gray =(R*77+G*151+B*28)>>8;
     */
    public static final int GRAY_ALGORITHM_DISPLACEMENT = 2;
    /**
     * 平均值法 Gray=（R+G+B）/3;
     */
    public static final int GRAY_ALGORITHM_AVERAGE = 3;

    private BitmapUtils() {

    }

    /**
     * 计算宽高缩放比例的合适采样率: inSampleSize
     *
     * @param options       Options options
     * @param requestWidth  需要的宽度
     * @param requestHeight 需要的高度
     * @return inSampleSize 任何<1的值都会被设置为1
     */
    public static int calculateInSampleSize(Options options, int requestWidth, int requestHeight) {
        int inSampleSize = 1;
        if (requestWidth <= 0 || requestHeight <= 0) return inSampleSize;

        if (requestWidth < options.outWidth || requestHeight < options.outHeight) {
            int widthRatio = Math.round((float) options.outWidth / (float) requestWidth);
            int heightRatio = Math.round((float) options.outHeight / (float) requestHeight);
            int maxRatio = Math.max(widthRatio, heightRatio);
            if (maxRatio > 1) {
                inSampleSize = maxRatio;
            }
        }
        return inSampleSize;
    }

    /**
     * 获取图片Bitmap
     *
     * @param path          图片路径
     * @param requestWidth  需要的宽度
     * @param requestHeight 需要的高度
     * @param config        默认Bitmap.Config.ARGB_8888
     * @return
     */
    public static Bitmap decodeFile(String path, int requestWidth, int requestHeight, Bitmap.Config config) {
        if (config == null) {
            config = Bitmap.Config.ARGB_8888;
        }
        Options options = new Options();
        //只获取图片的宽高
        if (requestWidth > 0 && requestHeight > 0) {
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
            options.inSampleSize = calculateInSampleSize(options, requestWidth, requestHeight);
        }
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = config;
        return BitmapFactory.decodeFile(path, options);
    }

    /**
     * 获取图片Bitmap
     *
     * @param path         图片路径
     * @param inSampleSize 压缩比 宽高分别为:1/inSampleSize,大小变为:inSampleSize的平方分之1
     * @param config       默认Bitmap.Config.ARGB_8888
     * @return
     */
    public static Bitmap decodeFile(String path, int inSampleSize, Bitmap.Config config) {
        if (config == null) {
            config = Bitmap.Config.ARGB_8888;
        }
        Options options = new Options();

        options.inJustDecodeBounds = false;
        options.inPreferredConfig = config;
        options.inSampleSize = Math.max(inSampleSize, 1);
        return BitmapFactory.decodeFile(path, options);
    }

    /**
     * 获取图片Bitmap
     *
     * @param resources
     * @param id            资源id
     * @param requestWidth
     * @param requestHeight
     * @param config
     * @return
     */
    public static Bitmap decodeResource(Resources resources, int id, int requestWidth, int requestHeight, Bitmap.Config config) {
        if (config == null) {
            config = Bitmap.Config.ARGB_8888;
        }
        Options options = new Options();
        //只获取图片的宽高
        if (requestWidth > 0 && requestHeight > 0) {
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeResource(resources, id, options);
            options.inSampleSize = calculateInSampleSize(options, requestWidth, requestHeight);
        }
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = config;
        return BitmapFactory.decodeResource(resources, id, options);
    }

    /**
     * 质量压缩 Bitmap,
     * bitmap的宽高,占用内存不会变化,
     * 它是在保持像素的前提下改变图片的位深及透明度等，来达到压缩图片的目的
     * 适合去传递二进制的图片数据
     *
     * @param bitmap
     * @param quality 0-100 (0:最低质量,100:最高质量)
     * @return
     */
    public static byte[] compressQuality(Bitmap bitmap, int quality) {
        if (bitmap == null) return null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        boolean compress = bitmap.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream);
        if (compress) {
            byte[] bytes = byteArrayOutputStream.toByteArray();
            try {
                byteArrayOutputStream.close();
                return bytes;
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }


    /**
     * 压缩bitmap到指定的大小
     * 质量压缩,请不在在主线程中使用
     * 压缩太厉害会导致图片模糊
     *
     * @param bitmap
     * @param maxSize 压缩后byte[]的最大size 单位KB
     * @return
     */
    public static byte[] compressQualityTo(Bitmap bitmap, int maxSize) {
        if (bitmap == null) return null;
        maxSize = maxSize * 1024;
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bao);
        int length = bao.size();
        while (length > maxSize) {
            quality -= 10;
            if (quality < 0) {
                break;
            }
            bao.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bao);
            length = bao.size();
            Log.i(TAG, "compressTo:quality=" + quality + ",length=" + length);
        }
        byte[] bytes = bao.toByteArray();
        try {
            bao.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    /**
     * 根据path获取图片,并压缩到指定大小,一般用于图片上传
     *
     * @param path          图片路径
     * @param requestWidth  需要的宽度 默认720
     * @param requestHeight 需要的高度 默认1280
     * @param maxSize       转换成byte[]后的最大大小 单位kb
     * @return
     */
    public static byte[] compressTo(String path, int requestWidth, int requestHeight, int maxSize) {
        int width = requestWidth > 0 ? requestWidth : 720;
        int height = requestHeight > 0 ? requestHeight : 1080;
        //先获取到指定宽高的bitmap
        Bitmap bitmap = decodeFile(path, width, height, Bitmap.Config.ARGB_8888);
        //压缩
        return compressQualityTo(bitmap, maxSize);
    }

    /**
     * 根据path获取图片,并压缩到指定大小(默认宽高[720,1280]),一般用于图片上传
     *
     * @param path    图片路径
     * @param maxSize 转换成byte[]后的最大大小 单位kb
     * @return
     */
    public static byte[] compressTo(String path, int maxSize) {
        return compressTo(path, 0, 0, maxSize);
    }

    /**
     * 水平镜像
     */
    public static Bitmap getMirrorHorizontal(Bitmap bitmap) {
        if (bitmap == null) return null;
        Matrix matrix = new Matrix();
        matrix.postScale(-1, 1); // 镜像水平翻转
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    /**
     * 垂直镜像
     */
    public static Bitmap getMirrorVertical(Bitmap bitmap) {
        if (bitmap == null) return null;
        Matrix matrix = new Matrix();
        matrix.postScale(1, -1); // 镜像水平翻转
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }


    /**
     * 创建圆形图片
     *
     * @param source
     * @return
     * @deprecated 废弃原因:从左边开始剪切的,没有居中
     * see {@link #toRoundBitmap(Bitmap, float, Bitmap.Config)}
     */
    @Deprecated
    public static Bitmap createCircleBitmap(Bitmap source) {
        int length = Math.min(source.getWidth(), source.getHeight());
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setAntiAlias(true);
        Bitmap target = Bitmap.createBitmap(length, length, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(target);
        canvas.drawCircle(length >> 1, length >> 1, length >> 1, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(source, 0, 0, paint);
        return target;
    }

    /**
     * 把bitmap剪切为圆形图片,中间开始剪切
     *
     * @param bitmap 原图
     * @param ratio  剪切原图大小的百分比 默认：1
     * @param config {@link Bitmap.Config} 默认值{@link Bitmap.Config#ARGB_4444}
     * @return
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap, float ratio, Bitmap.Config config) {
        if (bitmap == null) {
            return null;
        }
        if (config == null) {
            config = Bitmap.Config.ARGB_4444;
        }
        if (ratio <= 0 || ratio > 1) {
            ratio = 1;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        //根据比例在图片中间取正方形
        //正方形的边长
        int size = (int) (Math.min(width, height) * ratio);
        //图片中取得正方形的坐标
        Rect src = new Rect();
        src.left = (width - size) / 2;
        src.top = (height - size) / 2;
        src.right = src.left + size;
        src.bottom = src.top + size;
        //新的画布的区域
        Rect dst = new Rect(0, 0, size, size);

        //定义输出图片
        Bitmap outBitmap = Bitmap.createBitmap(size, size, config);
        Canvas canvas = new Canvas(outBitmap);
        //背景透明
        canvas.drawColor(Color.TRANSPARENT);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        //中心画圆
        canvas.drawCircle(size >> 1, size >> 1, size >> 1, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return outBitmap;
    }

    /**
     * 把bitmap剪切为圆形图片中间开始剪切
     *
     * @param bitmap
     * @return
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap) {
        return toRoundBitmap(bitmap, 1, null);
    }

    /**
     * 生成圆角图片
     *
     * @param bitmap  原图
     * @param corners 角度
     * @param lt      左上角
     * @param lb      左下角
     * @param rt      右上角
     * @param rb      右下角
     * @return
     */
    public static Bitmap toCornersBitmap(Bitmap bitmap, int corners, boolean lt, boolean rt, boolean rb, boolean lb) {
        if (bitmap == null) {
            return null;
        }
        if (corners <= 0 || !(lt || lb || rt || rb)) {
            return bitmap;
        }
        Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(outBitmap);
        Path cornersPath = CanvasUtils.getCornersPath(canvas, corners, lt, rt, rb, lb);
        if (cornersPath != null) {
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setAntiAlias(true);
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.RED);
            //画路径,并填充
            canvas.drawPath(cornersPath, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, 0, 0, paint);
            return outBitmap;

        } else {
            return bitmap;
        }
    }

    /**
     * 生成圆角图片,4个角
     *
     * @param bitmap  原图
     * @param corners 角度
     * @return
     */
    public static Bitmap toCornersBitmap(Bitmap bitmap, int corners) {
        return toCornersBitmap(bitmap, corners, true, true, true, true);
    }

    /**
     * 创建纯色的Bitmap支持圆角
     *
     * @param color   颜色
     * @param width   图片宽
     * @param height  图片高
     * @param config  默认值{@link Bitmap.Config#ARGB_8888}
     * @param corners 角度
     * @param lt      左上角
     * @param rt      右上角
     * @param rb      右下角
     * @param lb      左下角
     * @return Bitmap
     */
    public static Bitmap createBitmap(int color, int width, int height, Bitmap.Config config, int corners, boolean lt, boolean rt, boolean rb, boolean lb) {
        if (config == null) {
            config = Bitmap.Config.ARGB_8888;
        }
        Bitmap outBitmap = Bitmap.createBitmap(width, height, config);
        Canvas canvas = new Canvas(outBitmap);
        //获取圆角路径
        Path cornersPath = CanvasUtils.getCornersPath(canvas, corners, lt, rt, rb, lb);
        if (cornersPath != null) {
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(color);
            paint.setAntiAlias(true);
            paint.setStyle(Paint.Style.FILL);
            canvas.drawPath(cornersPath, paint);
        } else {
            canvas.drawColor(color);
        }
        return outBitmap;
    }

    /**
     * 创建纯色的Bitmap
     *
     * @param color  颜色
     * @param width  图片宽
     * @param height 图片高
     * @param config 默认值{@link Bitmap.Config#ARGB_8888}
     * @return Bitmap
     */
    public static Bitmap createBitmap(int color, int width, int height, Bitmap.Config config) {
        if (config == null) {
            config = Bitmap.Config.ARGB_8888;
        }
        Bitmap outBitmap = Bitmap.createBitmap(width, height, config);
        Canvas canvas = new Canvas(outBitmap);
        canvas.drawColor(color);
        return outBitmap;
    }

    /**
     * 创建纯色的圆形Bitmap
     *
     * @param color  颜色
     * @param radius 图片半径
     * @param config 默认值{@link Bitmap.Config#ARGB_8888}
     * @return Bitmap
     */
    public static Bitmap createRoundBitmap(int color, int radius, Bitmap.Config config) {
        if (config == null) {
            config = Bitmap.Config.ARGB_8888;
        }
        Bitmap outBitmap = Bitmap.createBitmap(radius, radius, config);
        Canvas canvas = new Canvas(outBitmap);
        Path roundPath = CanvasUtils.getRoundPath(canvas);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
        paint.setColor(color);
        canvas.drawPath(roundPath, paint);
        return outBitmap;
    }


    /**
     * 把图片用Base64编码转换成字符串
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToString(Bitmap bitmap) {
        byte[] bytes = compressQuality(bitmap, 100);
        byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
        return new String(encode);
    }

    /**
     * 把字符串转化为bitmap
     *
     * @param encodeString
     * @return
     */
    public static Bitmap stringToBitmap(String encodeString) {
        byte[] bytes = Base64.decode(encodeString, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     * 获取视频缩略图
     *
     * @param path
     * @return
     */
    public static Bitmap createVideoThumbnail(String path) {
        return ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.MICRO_KIND);
    }

    public static boolean keepBitmap(Bitmap bitmap, int quality, Bitmap.CompressFormat format, String path) {
        if (format == null) {
            String suffix = FileUtils.getSuffix(path);
            if (suffix.equalsIgnoreCase("png")) {
                format = Bitmap.CompressFormat.PNG;
            } else if (suffix.equalsIgnoreCase("webp")) {
                format = Bitmap.CompressFormat.WEBP;
            } else {
                format = Bitmap.CompressFormat.JPEG;
            }
        }
        FileOutputStream fos = null;
        boolean compress = false;
        try {
            fos = new FileOutputStream(new File(path));
            compress = bitmap.compress(format, quality, fos);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return compress;

    }

    /**
     * 保存bitmap
     *
     * @param bitmap
     * @param quality quality 0-100 (0:最低质量,100:最高质量)
     * @param path
     */
    public static boolean keepBitmap(Bitmap bitmap, int quality, String path) {
        return keepBitmap(bitmap, quality, null, path);
    }

    /**
     * 绘制文字到中间
     *
     * @param context
     * @param bitmap
     * @param text
     * @param sizeSp  文字大小(sp)
     * @param color   文字颜色
     * @return
     */
    public static Bitmap drawTextToCenter(Context context, Bitmap bitmap, String text,
                                          int sizeSp, int color) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(color);
        paint.setTextSize(ResourceUtils.spTopx(sizeSp));
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        return drawTextToBitmap(context, bitmap, text, paint, bounds,
                (bitmap.getWidth() - bounds.width()) / 2,
                (bitmap.getHeight() + bounds.height()) / 2);
    }

    /**
     * 绘制文字到中间
     *
     * @param context
     * @param bitmap
     * @param text
     * @param textWidthRatioWidth 文字占用的宽度和图片宽度的比
     * @param color               文字颜色
     * @return
     */
    public static Bitmap drawTextToCenterWidthRatio(Context context, Bitmap bitmap, String text,
                                                    float textWidthRatioWidth, int color) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(color);
        if (textWidthRatioWidth > 1 || textWidthRatioWidth < 0) {
            textWidthRatioWidth = 1;
        }
        int textWidth = (int) (bitmap.getWidth() * textWidthRatioWidth);
        paint.setTextSize(measureTextSize(text, textWidth, bitmap.getHeight()));
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        return drawTextToBitmap(context, bitmap, text, paint, bounds,
                (bitmap.getWidth() - bounds.width()) / 2,
                (bitmap.getHeight() + bounds.height()) / 2);
    }

    /**
     * 限制文本的最大宽高,测量出最合适的文字大小
     *
     * @param text      文本
     * @param maxWidth  文本占用的最大宽度
     * @param maxHeight 文本占用的最大高度
     * @return textSize 最合适的文字大小
     */
    public static float measureTextSize(String text, int maxWidth, int maxHeight) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setAntiAlias(true);
        Rect bounds = new Rect();

        int textSize = maxWidth / text.length();
        paint.setTextSize(textSize);
        paint.getTextBounds(text, 0, text.length(), bounds);
        int w = bounds.right - bounds.left;
        int h = bounds.bottom - bounds.top;
        LogUtils.e(TAG, "measureTextSize:textSize=" + textSize);
        if (w > maxWidth || h > maxHeight) {
            //宽高至少1个超出范围
            textSize -= 2;
            for (; textSize > 2; textSize -= 2) {
                if (DEBUG) {
                    LogUtils.d(TAG, "measureTextSize:textSize=" + textSize);
                }
                paint.setTextSize(textSize);
                paint.getTextBounds(text, 0, text.length(), bounds);
                w = bounds.right - bounds.left;
                h = bounds.bottom - bounds.top;
                if (w <= maxWidth && h <= maxHeight) {
                    break;
                }
            }
        } else {
            //宽高没有超出范围
            textSize += 2;
            for (; textSize < Integer.MAX_VALUE; textSize += 2) {
                if (DEBUG) {
                    LogUtils.d(TAG, "measureTextSize:textSize=" + textSize);
                }
                paint.setTextSize(textSize);
                paint.getTextBounds(text, 0, text.length(), bounds);
                w = bounds.right - bounds.left;
                h = bounds.bottom - bounds.top;
                if (w >= maxWidth || h >= maxHeight) {
                    break;
                }
            }
            textSize -= 2;
        }
        return textSize;
    }

    //图片上绘制文字
    private static Bitmap drawTextToBitmap(Context context, Bitmap bitmap, String text,
                                           Paint paint, Rect bounds, int paddingLeft, int paddingTop) {
        Bitmap.Config bitmapConfig = bitmap.getConfig();

        paint.setDither(true); // 获取跟清晰的图像采样
        paint.setFilterBitmap(true);// 过滤一些
        if (bitmapConfig == null) {
            bitmapConfig = Bitmap.Config.ARGB_8888;
        }
        bitmap = bitmap.copy(bitmapConfig, true);
        Canvas canvas = new Canvas(bitmap);

        canvas.drawText(text, paddingLeft, paddingTop, paint);
        return bitmap;
    }

    /**
     * 预览数据转化为bitmap
     *
     * @param data        预览数据
     * @param camera      Camera
     * @param preRotation preRotation 预览角度
     * @return
     */
    public static Bitmap previewDataToBitmap(byte[] data, Camera camera, int preRotation) {
        Camera.Parameters parameters = camera.getParameters();
        Camera.Size previewSize = parameters.getPreviewSize();
        //格式成YUV格式
        YuvImage yuvimage = new YuvImage(data, parameters.getPreviewFormat(), previewSize.width, previewSize.height, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 100, baos);
        byte[] bytes = baos.toByteArray();
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        bitmap = rotate(bitmap, preRotation);
        return bitmap;
    }

    /**
     * 选择bitMap
     *
     * @param bitmap
     * @param rotation
     * @return
     */
    public static Bitmap rotate(Bitmap bitmap, int rotation) {
        Matrix matrix = new Matrix();
        matrix.setRotate(rotation);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
    }

    /**
     * 调整Bitmap的大小
     *
     * @param bitmap
     * @param requestW     需要的宽
     * @param requestH     需要的高
     * @param inProportion 是否等比例缩放:
     * @return
     */
    public static Bitmap scale(Bitmap bitmap, int requestW, int requestH, boolean inProportion) {
        int srcW = bitmap.getWidth();
        int srcH = bitmap.getHeight();
        float scaleW = ((float) requestW) / srcW;
        float scaleH = ((float) requestH) / srcH;
        Matrix matrix = new Matrix();
        if (!inProportion) {
            matrix.postScale(scaleW, scaleH);
        } else {
            float min = Math.min(scaleW, scaleH);
            matrix.postScale(min, min);
        }
        return Bitmap.createBitmap(bitmap, 0, 0, srcW, srcH, matrix, true);

    }

    /**
     * 图片灰度变换
     * 耗时操作,请在线程中执行
     * 参考资料:https://baike.baidu.com/item/%E7%81%B0%E5%BA%A6%E5%80%BC/10259111?fr=aladdin  Gamma校正算法
     *
     * @param bitmap
     * @param algorithm 算法{@link #GRAY_ALGORITHM_GAMMA,#GRAY_ALGORITHM_FLOAT,#GRAY_ALGORITHM_DISPLACEMENT,#GRAY_ALGORITHM_AVERAGE}
     * @return
     */
    public static Bitmap toGrayScale(Bitmap bitmap, int algorithm) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int pixelsLength = width * height;
        int[] pixels = new int[pixelsLength];
        int[] pixelsResult = new int[pixelsLength];
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
        for (int i = 0; i < pixels.length; i++) {
            int clr = pixels[i];
            int alpha = clr & 0xFF000000;
            int red = (clr & 0x00ff0000) >> 16; //取高两位
            int green = (clr & 0x0000ff00) >> 8; //取中两位
            int blue = clr & 0x000000ff; //取低两位
//            Log.d(TAG, "toGrayScale:red=" + red + ",green=" + green + ",blue=" + blue);
            int gray;
            if (algorithm == GRAY_ALGORITHM_FLOAT) {
                //浮点法 Gray=R*0.3+G*0.59+B*0.11
                gray = (int) (red * 0.3 + green * 0.59 + blue * 0.11);
            } else if (algorithm == GRAY_ALGORITHM_DISPLACEMENT) {
                //移位法 Gray =(R*77+G*151+B*28)>>8;
                gray = (red * 77 + green * 151 + blue * 28) >> 8;
            } else if (algorithm == GRAY_ALGORITHM_AVERAGE) {
                //平均值法 Gray=（R+G+B）/3;
                gray = (red + green + blue) / 3;
            } else {
                //默认 Gamma校正算法
                gray = (int) Math.pow((Math.pow(red, 2.2) + Math.pow((1.5 * green), 2.2) + Math.pow((0.6 * blue), 2.2)) / (1 + Math.pow(1.5, 2.2) + Math.pow(0.6, 2.2)), 1 / 2.2);
            }
            int newColor = alpha | (gray << 16) | (gray << 8) | gray;
            pixelsResult[i] = newColor;
        }
        return Bitmap.createBitmap(pixelsResult, 0, width, width, height, Bitmap.Config.ARGB_8888);
    }

    /**
     * 图片灰度变换,默认Gamma校正算法
     * @param bitmap
     * @return
     */
    public static Bitmap toGrayScale(Bitmap bitmap) {
        return toGrayScale(bitmap, GRAY_ALGORITHM_GAMMA);
    }


}
